<?php

namespace App\Http\Controllers;

use App\Models\Client;
use App\Models\StatisticsConsume;
use Request;
use DB;
use Hash;



class CommonController extends Controller
{
    //资方余额不足提醒
    public function owe(){
        die;
        $clients = Client::select('sign', 'id','name','cash','verify', 'protocol', 'client_url')->get();
        if(count($clients)){
            foreach ($clients as $val){
                if($val->cash <= 2000 && $val->verify == 1){//1 未发送 0 已发送
                    $protocol = $val->protocol;
                    $client_url = $val->client_url;
                    $send_url = $protocol.'://'.$client_url.'/api/jcz/get/admin/mobile/tips';
                    $par = 'sign='.$val->sign;
                    $res = json_decode($this->request_post($send_url, $par), true);
                    if(!empty($res['data'])){
                        $data['mobile'] = $res['data'];
                        $data['name'] = $val->name;
                        $data['attr'] = 'zifang';
                        $this->sendmsg($data);
                    }

                    //调用短信接口
                    $data['mobile'] = '15836,18925';
                    $data['name'] = $val->name;
                    $data['attr'] = 'shangwu';
                    $ret = $this->sendmsg($data);
                    if($ret['code'] == 0){
                        $val->verify = 0;
                        $val->save();
                    }
                }elseif($val->cash > 2000 && $val->verify == 0){
                    $val->verify = 1;
                    $val->save();
                }
            }
        }
        echo 'success';
        return;
    }
    //短信方法
    protected function sendmsg($sendData){
        $attr = $sendData['attr'];
        $mobile = $sendData['mobile'];
        $name = $sendData['name'];
        try {
            $tm = date('YmdHms');
            $pw = config('sendtipmsg.pw');
            $data['uid'] = config('sendtipmsg.uid');
            $data['mb']  = $mobile;
            if($attr == 'shangwu'){
                $data['ms']  = str_replace('{ower}', $name, config('sendtipmsg.owe'));
            }elseif($attr == 'zifang'){
                $data['ms']  = str_replace('北斗星', $name, config('sendtipmsg.client_owe'));
            }
            $data['tm']  = $tm;
            $data['pw']  = md5($pw . $tm);

            $req_url = "http://".config('sendtipmsg.ip')."/send.do?uid=".$data['uid']."&pw=".config('sendtipmsg.pw')."&mb=".$data['mb']."&ms=".$data['ms']."&ex=77";
            $dataStr     = '';
            foreach ($data as $key => $val) {
                $dataStr .= $key . '=' . $val . '&';
            }
            $send_result = $this->request_post($req_url, $dataStr);
            @file_put_contents('../storage/logs/send_owe_msg_'.date('Ym').'.log', date('Y-m-d H:i:s'). '&phone='.$mobile.'&recode='.$send_result.PHP_EOL, FILE_APPEND);
            return ['code' => 0, 'info' => '发送成功'];
        } catch (\Exception $exception) {
            @file_put_contents('../storage/logs/send_owe_msg_exc_'.date('Ym').'.log', date('Y-m-d H:i:s'). '|client'.$exception->getMessage().PHP_EOL, FILE_APPEND);
        }
    }
    //curl
    protected function request_post($url = '', $param = '') {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl  = $url;
        $curlPost = $param;
        $ch       = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL, $postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        curl_setopt($ch, CURLOPT_TIMEOUT,30);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);

        return $data;
    }
    //管理员登录的时候发送的验证码
    public function sendLoginCode(){
        $name = Request::input('name');
        $res = DB::table('admin_users')->where('username', $name)->first();

        if(!$res){
            return ['code' => -1, 'text' => '账号或密码错误'];
        }
        //发送短信
        $this->sendVcode($res->mobile);
        return ['code' => 0, 'text' => '发送成功'];
    }
    //发送验证码
    protected function sendVcode($mobile){
        $vcode = rand(1111, 9999);
        $vremark = 'vcode_'.$mobile;
        session()->put($vremark, $vcode);
        session()->save();
        try {
            $tm = date('YmdHms');
            $pw = config('sendtipmsg.pw');
            $data['uid'] = config('sendtipmsg.uid');
            $data['mb']  = $mobile;
            $data['ms']  = str_replace('{vcode}', $vcode, config('sendtipmsg.vcode'));
            $data['tm']  = $tm;
            $data['pw']  = md5($pw . $tm);

            $req_url = "http://".config('sendtipmsg.ip')."/send.do?uid=".$data['uid']."&pw=".config('sendtipmsg.pw')."&mb=".$data['mb']."&ms=".$data['ms']."&ex=77";
            $dataStr     = '';
            foreach ($data as $key => $val) {
                $dataStr .= $key . '=' . $val . '&';
            }
            $send_result = $this->request_post($req_url, $dataStr);
            @file_put_contents('../storage/logs/send_login_msg_'.date('Ym').'.log', date('Y-m-d H:i:s'). '||ms='.$data['ms'].'&phone='.$mobile.'&recode='.$send_result.PHP_EOL, FILE_APPEND);
            return ['code' => 0, 'info' => '发送成功'];
        } catch (\Exception $e) {
            @file_put_contents('../storage/logs/send_login_msg_exc_'.date('Ym').'.log', 'date='.date('Y-m-d H:i:s').'||exc='.$e->getMessage().PHP_EOL, FILE_APPEND);
        }
    }
    //接受资方的风控数据的统计
    public function getRiskStatistic(){
        $res = Request::all();
        $sign = $res['sign'];
        $time = time() - 3600 * 2;//两个小时以前的
        $client = Client::where('sign', $sign)->first();
        if(!count($client)){
            return ['code' => -1, 'text' => 'fail'];
        }
        $statics = StatisticsConsume::where('date', date('Y-m-d', $time))->where('name', $sign)->first();
        if(!count($statics)){
            $statics = new StatisticsConsume();
            $statics->date = date('Y-m-d', $time);
            $statics->name = $sign;
        }
        $statics->verify = $res['verify'];
        $statics->mobile = $res['mobile'];
        $statics->bankcard = $res['bankcard'];
        $statics->access = $res['access'];
        $statics->confidence = $res['confidence'];
        $statics->message = $res['message'];
        $statics->risk = $res['risk'];
        $statics->save();
        return ['code' => 0, 'text' => 'ok'];
    }



    //获取运营商告
    public function carrier(Request $request)
    {
        $mobile = $request->input('mobile', '');
        $riskType = GlobalConfig::withoutGlobalScopes()->where('name', 'risktype')->value('value');
        $filter_switch = 2;
        if($riskType == 1){
            $zhimiReport = RiskZhimiReport::withoutGlobalScopes()->select('report_data')->where('mobile', $mobile)->first();
            $report = json_decode($zhimiReport['report_data'], true);

            //过滤电话号码
            if(isset($report['data']['communication_time_bucket_info'])){
                foreach ($report['data']['communication_time_bucket_info'] as &$val){
                    if(isset($val['phone_times']) && $val['phone_times'] && mb_strlen($val['phone_times']) > 7){
                        if($filter_switch == 1){//脱敏
                            $val['phone_times'] = substr_replace($val['phone_times'], '***', '3', '4');
                        }else{
                            $val['phone_times'] = $val['phone_times'];
                        }
                    }
                }
            }

            if(isset($report['data']['top10_call_count'])){
                foreach ($report['data']['top10_call_count'] as &$val){
                    if(isset($val['phone_number']) && $val['phone_number'] && mb_strlen($val['phone_number']) > 7){
                        if($filter_switch == 1){
                            $val['phone_number'] = substr_replace($val['phone_number'], '***', '3', '4');
                        }else{
                            $val['phone_number'] = $val['phone_number'];
                        }
                    }
                }
            }

            if(isset($report['data']['top10_call_time'])){
                foreach ($report['data']['top10_call_time'] as &$val){
                    if(isset($val['phone_number']) && $val['phone_number'] && mb_strlen($val['phone_number']) > 7){
                        if($filter_switch == 1){
                            $val['phone_number'] = substr_replace($val['phone_number'], '***', '3', '4');
                        }else{
                            $val['phone_number'] = $val['phone_number'];
                        }
                    }
                }
            }

            if(isset($report['data']['top10_single_call_time'])){
                foreach ($report['data']['top10_single_call_time'] as &$val){
                    if(isset($val['phone_number']) && $val['phone_number'] && mb_strlen($val['phone_number']) > 7){
                        if($filter_switch == 1){
                            $val['phone_number'] = substr_replace($val['phone_number'], '***', '3', '4');
                        }else{
                            $val['phone_number'] = $val['phone_number'];
                        }
                    }
                }
            }

            if(isset($report['data']['label_info'])){
                foreach ($report['data']['label_info'] as &$val){
                    if(isset($val['phone_number']) && $val['phone_number'] && mb_strlen($val['phone_number']) > 7){
                        if($filter_switch == 1){
                            $val['phone_number'] = substr_replace($val['phone_number'], '***', '3', '4');
                        }else{
                            $val['phone_number'] = $val['phone_number'];
                        }
                    }
                }
            }

            $risktype = 1;
            if(!count($report)){
                $menghuaReport = RiskMenghuaReport::withoutGlobalScopes()->select('original_data')->where('mobile', $mobile)->first();
                if(count($menghuaReport)){
                    $report = json_decode($menghuaReport['original_data'], true);
                    $risktype = 2;
                }else{
                    $report = [];
                    $risktype = 1;
                }
            }
        }else{
            $menghuaReport = RiskMenghuaReport::withoutGlobalScopes()->select('original_data')->where('mobile', $mobile)->first();
            $report = json_decode($menghuaReport['original_data'], true);
            $risktype = 2;
            if(!count($report)){
                $zhimiReport = RiskZhimiReport::withoutGlobalScopes()->select('report_data')->where('mobile', $mobile)->first();
                if(count($zhimiReport)){
                    $report = json_decode($zhimiReport['report_data'], true);
                    $risktype = 1;
                }else{
                    $report = [];
                    $risktype = 2;
                }
            }
        }

        $web_data = [
            'rspCode' => 0,
            'data' => $report,
            'message' => '查询成功',
            'risktype' => $risktype
        ];
        return Response()->json($web_data);
    }


}




















